﻿using Aliyun.OSS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NSJL.Plugin.Third.Aliyun
{
    public class AliyunOss
    {

        public static string endpoint = "oss-cn-shanghai.aliyuncs.com";
        public static string accessKeyId = "";
        public static string accessKeySecret = "";
        public string bucketName = "";
        public AliyunOss(string name= "backup-ts")
        {
            bucketName = name;
        }

        public string GetAliyunImage(string key)
        {
            //OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            //var object1 = client.GetObject(bucketName, key);
            var img = "http://" + bucketName + "." + endpoint + "/" + key;
            return img;
        }

        public byte[] GetAliyunByte(string key)
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                var obj = client.GetObject(bucketName, key);
                var bytes = new byte[obj.ContentLength];
                int count = (int)obj.ContentLength;
                using (var requestStream = obj.Content)
                {
                    int offset = 0;
                    while (count > 0)
                    {
                        int n = requestStream.Read(bytes, offset, count);
                        if (n == 0) break;
                        count -= n;
                        offset += n;
                    }
                }
                return bytes;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public void DeleteObject(string objectName)
        {
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                client.DeleteObject(bucketName, objectName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete object failed. {0}", ex.Message);
            }
        }
        public string PutImage(string path,string key=null)
        {
            key = key??Guid.NewGuid().ToString("N");
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            client.PutObject(bucketName, key, path);
            return key;
        }

        public string PutImage(Stream content, string key = null)
        {
            key = key ?? Guid.NewGuid().ToString("N");
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            client.PutObject(bucketName, key, content);
            return key;
        }


    }
}
